<?php
class Utils{
    private $appid;
    private $appsecret;
    public function __construct($appid,$appsecret) {
        $this->appid = $appid;
        $this->appsecret = $appsecret;
    }

    /**
     * 获取ticket
     * @param  [type] $data [description]
     * @return [type]       二维码ticket
     */
    public function getTicket($data) {
       $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token={$this->getAccessToken()}";  
       $result = $this->https_request($url,$data);
       return $result["ticket"];
    }

    /**
     * 处理用户请求
     * @return [type] [description]
     */
    public function responseMsg(){
        // 接受原生的xml字符串
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!$postStr) {
            echo "post data error";
            exit;
        }
        // 把原生字符串转化成对象
        $postObj=simplexml_load_string($postStr,'SimpleXMLElement', LIBXML_NOCDATA );
        // 接受消息的类型
        $MsgType=$postObj->MsgType;
        if($MsgType == "event") {
            $Event=$postObj->Event;
            if($Event == 'subscribe') {
               $servername = "47.94.244.200:2225";
                $username = "admin";
                $password = "li555&666";
                $dbname = "test";

                try {
                    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
                    // 设置 PDO 错误模式，用于抛出异常
                    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $sql = "insert into user (openid,keykk) values('{$postObj->FromUserName}','{$postObj->EventKey}')";
                    // 使用 exec() ，没有结果返回 
                    $conn->exec($sql);
                    echo "新记录插入成功";
                }
                catch(PDOException $e)
                {
                    echo $sql . "<br>" . $e->getMessage();
                }
                // echo sprintf($str,$postObj->FromUserName,$postObj->ToUserName,time(),$postObj->MsgType,$postObj->Event,$postObj->EventKey,$postObj->Ticket);
            }
        }
    }
    

    /**
     * @获取access_token
     */
    public function getAccessToken() {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
        $res =  $this->https_request($url);
        return $res['access_token'];
    }

    /**
     * 模拟gei请求·和post请求
     * @param $url
     * @param string $data
     * @return mixed
     */
    public function https_request($url,$data=""){
        // 开启curl
        $ch=curl_init();
        // 设置传输选项
        // 设置传输地址
        curl_setopt($ch, CURLOPT_URL, $url);
        // 以文件流的形式返回
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($data) {
            // 以post方式
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }

        // 发送curl
        $request=curl_exec($ch);

        $tmpArr=json_decode($request,TRUE);

        if (is_array($tmpArr)) {
            return $tmpArr;
        }else{
            return $request;
        }
        // 关闭资源
        curl_close($ch);
    }

}